<?php
/*
  Microblog bot for game release notifications
  Copyright (C) 2017  Alexander Yakovlev

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

namespace Source;

use \Game;

class Itch extends Source {
  public $title = "Itch.io";
  protected function parse_tag($url) {
    $service = new \Sabre\Xml\Service();
    $xml = $this->get_text($url);
    $service->elementMap = [
      '{}item' => function(\Sabre\Xml\Reader $reader) {
        $game = new Game;
        $keyValue = \Sabre\Xml\Deserializer\keyValue($reader, '{}item');
        if (isset($keyValue['{}pubDate'])) {
          $game->date = strtotime($keyValue['{}pubDate']);
          if ($game->date < $this->period) {
            return $game;
          }
        }
        if (isset($keyValue['{}plainTitle'])) {
          $game->title = $keyValue['{}plainTitle'];
        }
        if (isset($keyValue['{}link'])) {
          $game->url = $keyValue['{}link'];
        }
        if (isset($keyValue['{}description'])) {
          $game->description = trim(strip_tags($keyValue['{}description'], '<p><a><br>'));
        }
        $game_page = $this->get_text($game->url);
        $this->dom->loadStr($game_page, []);
        $lines = $this->dom->find('.game_info_panel_widget tr');
        foreach ($lines as $line) {
          $text =  $line->find('td');
          if ($text->innerHtml == 'Author') {
            $game->author = strip_tags($text->nextSibling()->innerHtml);
          }
        }
        $this->games[] = $game;
        return $game;
      },
    ];
    $dom = $service->parse($xml);
  }
  protected function parse() {
    $this->parse_tag("https://itch.io/games/newest/tag-text-based.xml");
    $this->parse_tag("https://itch.io/games/newest/tag-interactive-fiction.xml");
  }
}
